package cn.ggy.service;

import cn.ggy.dao.AccountDao;
import cn.ggy.polo.Account;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import javax.annotation.Resource;

@Service
public class AccountServiceImpl implements AccountService {

    @Resource
    private AccountDao accountDao;

    @Autowired
    DataSourceTransactionManager transactionManager;

    /**
     * 俩人转账
     * @param account1
     * @param account2
     */
    @Override
    public void zhuanZhang(Account account1, Account account2) {

        //罗志祥给蝴蝶姐姐转了200
//        Double money1 =account1.getMoney()-200;
//        account1.setMoney(money1);
//
//        //蝴蝶姐姐收款200
//        Double money2 = account2.getMoney()+200;
//        account2.setMoney(money2);

        TransactionStatus transactionStatus = null;

        /**
         * 转了200
         */
        try {
            //设置事物的模板
            DefaultTransactionDefinition dtd = new DefaultTransactionDefinition();
            //是否是只读
            dtd.setReadOnly(false);
            //设置事物的等级
            dtd.setIsolationLevel(TransactionDefinition.ISOLATION_DEFAULT);
            //设置事务的传播行为  (没有事务要开启一个事务)
            dtd.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
            //获取状态(使用事务管理器调用方法然后再把参数传入即可)
            transactionStatus = transactionManager.getTransaction(dtd);

            accountDao.updateAccount(account1);

            //System.out.println(1/0);  //这时不加回滚事务就会出现钱已经转出去了但是对面没有收到
            accountDao.updateAccount2(account2);
            //(如果没有发生异常的话) 提交事务(根据状态提交)
            transactionManager.commit(transactionStatus);
        } catch (Exception e) {
            //回滚事务(根据状态回滚)
            transactionManager.rollback(transactionStatus);
            e.printStackTrace();
        }

    }

    @Override
    public void zhuanZhang2(Account account1, Account account2) {
        accountDao.updateAccount(account1);
//        System.out.println(1/0);
        accountDao.updateAccount2(account2);
    }

}

